import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Test extends JFrame implements KeyListener {
    JButton[] b = new JButton[3];
    int x, y;

    public Test() {
        setSize(300, 300);
        setVisible(true);
        setLayout(new FlowLayout());
        for (int i = 0; i <= 2; i++) {
            b[i] = new JButton(" " + i);
            b[i].addKeyListener(this);
            add(b[i]);
        }
        validate();
    }

    public void keyPressed(KeyEvent e) {
        JButton button = (JButton)e.getSource();
        x = button.getBounds().x;
        y = button.getBounds().y;

        if (e.getKeyCode() == KeyEvent.VK_UP) {
            y = y - 2;
            if (y <= 0)
                y = 300;
            button.setLocation(x, y);
        }
        else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            y = y + 2;
            if (y >= 300)
                y = 0;
            button.setLocation(x + 2, y);//就修改这个地方
        }
        else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            x = x - 2;
            if (x <= 0)
                x = 300;
            button.setLocation(x, y);
        }
        else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            x = x + 2;
            if (x >= 300)
                x = 0;
            button.setLocation(x, y);
        }
    }
    public void keyTyped(KeyEvent e) {

    }
    public void keyReleased(KeyEvent e) {

    }

    public static void main(String[] args) {
        Test win = new Test();
        win.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}
